package org.example.netty.zk;

import io.netty.util.CharsetUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.CreateMode;
import org.example.zk.ClientFactory;

public class SnowflakeIdWorker {
    private String pathPrefix = "/test/IDMaker/worker-";

    private String pathRegistered = null;

    transient CuratorFramework zkClient = null;

    private long nodeId = -1;

    private static final String ZOOKEEPER_ADDRESS = "localhost:2181";

    public static SnowflakeIdWorker instance = new SnowflakeIdWorker();

    public SnowflakeIdWorker() {
        zkClient = ClientFactory.createSimple(ZOOKEEPER_ADDRESS);
    }

    private void createNode() {
        try {
            // TODO 开始连接ZOOKEEPER
            zkClient.start();

            pathRegistered = zkClient.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                    .forPath(pathPrefix, pathPrefix.getBytes(CharsetUtil.UTF_8));
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            CloseableUtils.closeQuietly(zkClient);
        }
    }

    public long generatorId() {
        createNode();
        if (nodeId > 0)
            return nodeId;
        if (StringUtils.isBlank(pathRegistered))
            throw new RuntimeException("节点不存在");

        int preIndex = pathRegistered.indexOf(pathPrefix);
        nodeId = Long.parseLong(pathRegistered.substring(preIndex + pathPrefix.length()));
        return nodeId;
    }

    public static void main(String[] args) {
        System.out.println(new SnowflakeIdWorker().generatorId());
    }
}
